package beeboxes;


public class M1Card {
    private final static String TAG = M1Card.class.getSimpleName();

    private byte uid[];
    private int uid_len;
    private byte sak;
    private byte atqa[];

    private final static int UID_OFFSET = 0;
    private final static int UID_LENGTH = 4;
    private final static int BCC_OFFSET = UID_OFFSET + UID_LENGTH;
    private final static int BCC_LENGTH = 1;
    private final static int ASK_OFFSET = BCC_OFFSET + BCC_LENGTH;
    private final static int ASK_LENGTH = 1;
    private final static int ATQA_OFFSET = ASK_OFFSET + ASK_LENGTH;
    private final static int ATQA_LENGTH = 2;
    private final static int MANUFACTURE_OFFSET = ATQA_OFFSET + ATQA_LENGTH;
    private final static int MANUFACTURE_LENGTH = 8;

    public M1Card(byte[] rawData, int hex_len) {
        this.atqa = new byte[ATQA_LENGTH];
        int byte_len = hex_len / 2 + ((hex_len % 2 == 0) ? 0 : 1);
        //this.uid_len = UID_LENGTH + BCC_LENGTH;
        this.uid_len = byte_len;
        this.uid = new byte[this.uid_len];
        System.arraycopy(rawData, UID_OFFSET, this.uid, 0, this.uid_len);
        if (hex_len % 2 == 1) {
            shiftRightForZero(this.uid);
        }
        //System.arraycopy(rawData, ASK_OFFSET, this.sak, 0, ASK_LENGTH);
        this.sak = rawData[ASK_OFFSET];
        System.arraycopy(rawData, ATQA_OFFSET, this.atqa, 0, ATQA_LENGTH);
        //Log.d(TAG, "uid=" + String.valueOf(this.uid) + ",uid_len=" + this.uid_len + ",sak=" + this.sak + ",atqa=" + String.valueOf(this.atqa));
    }

    public byte[] getUid() {
        return this.uid;
    }

    public void setUid(byte[] uid) {
        if (uid == null) {
            return;
        }
        this.uid = new byte[uid.length];
        System.arraycopy(uid, 0, this.uid, 0, uid.length);
    }

    public int getUidLen() {
        return this.uid_len;
    }

    public void setUidLen(byte uid_len) {
        this.uid_len = uid_len & 0xFF;
    }

    public byte[] getAtqa() {
        return this.atqa;
    }

    public void setAtqa(byte[] atqa) {
        if (atqa == null) {
            return;
        }
        this.atqa = new byte[atqa.length];
        System.arraycopy(atqa, 0, this.atqa, 0, atqa.length);
    }

    public byte getSak() {
        return this.sak;
    }

    public void setSak(byte sak) {
        this.sak = sak;
    }

    public static void shiftRightForZero(byte[] bytes) {
        int len = bytes.length;
        for (int i = len - 1; i > 0; i--) {
            byte right = (byte) ((bytes[i] >> 4) & 0x0f);
            byte left = (byte) (bytes[i-1] & 0x0f);
            byte temp = (byte) (right | (left << 4));
            bytes[i] = temp;
        }
        bytes[0] = (byte) (bytes[0] >> 4);
    }

}
